#!/bin/sh

#
# Start and stop the afdsmgrd daemon.
#
# by Dario Berzano <dario.berzano@gmail.com>
#
# This script is conform to the LSB specifications and it is compatible with
# the chkconfig custom header format.
#

#
# chkconfig header
#

# chkconfig: 2345 99 0
# description: afdsmgrd, which stands for Analysis Facility Dataset Manager
#              Daemon, is a ROOT-based daemon that scans the stored datasets in
#              order to issue the actual data staging
# processname: afdsmgrd
# pidfile: /var/run/afdsmgrd.pid

#
# LSB header
#

### BEGIN INIT INFO
# Provides: afdsmgrd
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Short-Description: Dataset manager for PROOF-based AFs
# Description: afdsmgrd, which stands for Analysis Facility Dataset Manager
#              Daemon, is a ROOT-based daemon that scans the stored datasets in
#              order to issue the actual data staging
### END INIT INFO

# Source function library
if [ -r /lib/lsb/init-functions ]; then
  . /lib/lsb/init-functions
elif [ -r /etc/init.d/functions ]; then
  . /etc/init.d/functions
fi

# Get the configuration variables
if [ -r /etc/sysconfig/afdsmgrd ]; then
  . /etc/sysconfig/afdsmgrd
fi

[ -x $AFDSMGRD_PROG ] || exit 0

RETVAL=0
PROG=afdsmgrd

start() {
  echo -n "Starting $PROG..."
  pidofproc "$AFDSMGRD_PROG" > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    echo "done (already running)"
    return 0
  fi

  # Creates proper environment and logdir
  export LD_LIBRARY_PATH=$AFDSMGRD_LIBS:$LD_LIBRARY_PATH
  mkdir -p $AFDSMGRD_LOGDIR
  chown -R $AFDSMGRD_USER:$AFDSMGRD_GROUP $AFDSMGRD_LOGDIR
  touch $AFDSMGRD_LOGFILE
  chown $AFDSMGRD_USER:$AFDSMGRD_GROUP $AFDSMGRD_LOGFILE
  [ $AFDSMGRD_DEBUG -eq 1 ] && EXTRAOPTS=-d

  $AFDSMGRD_PROG -c $AFDSMGRD_CONF -R $AFDSMGRD_USER -b -l $AFDSMGRD_LOGFILE \
    -p $AFDSMGRD_PIDFILE $EXTRAOPTS
  RETVAL=$?

  [ $RETVAL -eq 0 ] && echo "done" || echo "failed"
  return $RETVAL
}

stop() {
  echo -n "Stopping $PROG..."
  killproc $AFDSMGRD_PROG
  RETVAL=$?
  [ $RETVAL -eq 0 ] && rm -f $AFDSMGRD_PIDFILE
  [ $RETVAL -eq 0 ] && echo "done" || echo "failed"
  return $RETVAL
}

#
# Entry point
#

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  status)
    status afdsmgrd
    RETVAL=$?
  ;;
  restart|reload)
    # Restarts the daemon; results in a start if daemon wasn't running
    stop
    start
  ;;
  condrestart)
    # Restarts the daemon only if it is running
    pidofproc "$AFDSMGRD_PROG" > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      stop
      start
    else
      echo "Not running, nothing to do"
    fi
  ;;
  *)
     echo  "Usage: $0 {start|stop|status|restart|reload|condrestart}"
     exit 1
  ;;
esac

exit $RETVAL
